package org.jeecg.modules.buyer.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.RedisPublicKeyPrefixConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.buyer.entity.MtBuyer;
import org.jeecg.modules.buyer.mapper.MtBuyerMapper;
import org.jeecg.modules.buyer.service.IMtBuyerService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @Description: 采购员信息表
 * @Author: jeecg-boot
 * @Date:   2023-12-07
 * @Version: V1.0
 */
@Service
public class MtBuyerServiceImpl extends ServiceImpl<MtBuyerMapper, MtBuyer> implements IMtBuyerService {

    private RedisUtil redisUtil;
    @Autowired
    private ISysUserService sysUserService;
    @Override
    public void saveAndCreateSysUser(MtBuyer mtBuyer) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //往user表中添加数据
        JSONObject user = new JSONObject();
        user.put("username", mtBuyer.getTel());//账号：客户手机号
        user.put("realname", mtBuyer.getBuyerName());//用户名称：客户名称
        user.put("password", mtBuyer.getTel());//密码：客户手机号
        user.put("phone", mtBuyer.getTel());//手机号
        user.put("confirmpassword", mtBuyer.getTel());
        user.put("useridentity", 1);//身份（1 普通成员 2 上级）
        user.put("userId", mtBuyer.getTel());
        user.put("activitisync", 1);//同步工作流引擎(1-同步,0-不同步)
        user.put("workNo", mtBuyer.getTel());//工号：手机号码
        user.put("usertype", 5);//0平台管理员 1服务商 2服务站 3工程师 4客户 5采购员
        //插入到user表中，并设置角色
        Result<SysUser> userResult = sysUserService.addUserAndRoleOfBuyer(user);
        redisUtil.removeAll(CacheConstant.SYS_DEPARTS_CACHE);
        redisUtil.removeAll(CacheConstant.SYS_DEPART_IDS_CACHE);
        if (!userResult.isSuccess()) {
            //报错，进行事务回滚
            throw new JeecgBootException(userResult.getMessage());
        }
        SysUser result = userResult.getResult();
        mtBuyer.setUserId(result.getUsername()); //账号绑定
        //往客户表里添加数据
        super.save(mtBuyer);
        String jsonString = JSON.toJSONString(mtBuyer);
        redisUtil.set(RedisPublicKeyPrefixConstant.CUSTOM + ":" + mtBuyer.getSysOrgCode() + ":" + mtBuyer.getCreateBy(), jsonString, 60 * 60 * 2);
    }
}
